package chat.network.tcp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.xkh.xkh.MyApplication;

import managers.UIHandler;

/**
 * Created by Administrator on 2015/12/29.
 */
public class IMMessageReceiver extends BroadcastReceiver {

    public static String CONNECTION_CLOSED = "im.CONNECTION_CLOSED";
    public static String CONNECTION_DESTROY = "im.CONNECTION_DESTROY";
    public static String GETBEOFFLINE = "im.GETBEOFFLINE";
    private Context context;

    @Override
    public void onReceive(final Context context, Intent it) {
        this.context = context;
        // 加大存活效率
        if (it.getAction().equals("android.intent.action.USER_PRESENT") || it.getAction().equals("android.intent.action.ACTION_POWER_CONNECTED") || it.getAction().equals("android.intent.action.ACTION_POWER_DISCONNECTED")) {
            this.startPushService();
            Log.i("解锁时","检查连接状态");
        }
        // 网络变化
        else if (it.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
            ConnectivityManager connectivityManager = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            this.onDevicesNetworkChanged(info);
        }
        // 连接关闭
        else if (it.getAction().equals(CONNECTION_CLOSED)) {

        }

        // 连接人工断开
        else if (it.getAction().equals(CONNECTION_DESTROY)) {
            Intent intent = new Intent(context, PushControlReceiver.class);
            intent.putExtra(PushService.SERVICE_ACTION, PushService.ACTION_DESTORY);
            context.startService(intent);
        }

        // 收到被强迫下线消息
        else if (it.getAction().equals(GETBEOFFLINE)) {
            UIHandler.uiHandler.sendEmptyMessage(0x0d);
        }
    }

    // 网络发生变化
    private void onDevicesNetworkChanged(NetworkInfo info) {
        if (info != null) {
            Log.i("网络可用","检查连接线程");
            startPushService();
        }
    }

    // 重连推送服务
    private void startPushService() {
        if (!MyApplication.isExitMust) {
            Intent intent = new Intent(this.context, PushControlReceiver.class);
            intent.putExtra(PushService.SERVICE_ACTION, PushService.ACTION_CONNECTION);
            context.sendBroadcast(intent);
        }

    }

}
